var map;
var loading  = 0; 

function warnclick(e) {
  // console.log("0000");
  map.setCenter(e.split(","));
}
$(function () {
  /*---------------------------------------------getCookie--------------------------------------------*/

  function getCookie(name) {
    var arr,
      reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if ((arr = document.cookie.match(reg))) {
      // return true;
      // console.log(arr[2]);
      return arr[2];
    } else {
      return false;
    }
  }
  /*----------------------------------------URL-------------------------------------------------*/

  var _url = "/prod-api";
  //  var _url = 'http://qingxie.ijingniu.cn/prod-api/biz/dataView/';
  /*----------------------------------------Authorization: Bearer {Token}------------------------*/
  var Token = getCookie("Admin-Token");
  // console.log(Token, "token");

  /*----------------------------------------GET-------------------------------------------------*/

  function getData(params, getCallback) {
    $.ajax({
      url: _url + params,
      headers: {
        Authorization: "Bearer " + Token,
      },
      processData: false,
      contentType: "application/json;charset=utf-8",
      type: "GET",
      dataType: "json",
      success(res) {
        getCallback(res);
      },
    });
  }
  /*---------------------------------------------15日度统计-warnCountList--------------------------------------------*/
  getData("/biz/dataView/warnCountList", function getCallback(res) {
    // console.log(res, "warnCountList");
    var monthNum = [];
    var monthTime = [];

    for (let index = 0; index < res.data.length; index++) {
      monthNum.push(res.data[index].num);
      monthTime.push(res.data[index].dt);
    }

    echarts_1(monthTime, monthNum);
  });
  /*---------------------------------------------实时监测-modemCount--------------------------------------------*/
  getData("/biz/dataView/modemCount", function getCallback(res) {
    // console.log(res, "modemCount");
    $("#preNum").html(res.data.preNum);
    $("#warnNum").html(res.data.warnNum);
    $("#total").html(res.data.total); //
    $("#netErrorNum").html(res.data.netErrorNum);

    // =================================================
    $("#okPercent").html(
      parseInt( (res.data.okNum / res.data.total)  * 100) + "%"
    );
    $("#netPercent").html(  parseInt(((res.data.total - res.data.netErrorNum) / res.data.total)  * 100) + "%"  )
  });
  /*---------------------------------------------设备分布---------------------------------------------*/
  getData("/biz/modem/list", function getCallback(res) {
    // console.log(res, "modemList-地图");
    gaode_map(res.rows);
  });
  /*---------------------------------------------24h检测---------------------------------------------*/

  getData("/biz/dataView/sensorCount", function getCallback(res) {
    console.log(res, "title 统计");
    // $("#deptCount").html(res.data.deptCount);

    // $("#modemCount").html(res.data.modemCount);
    // $("#all-warnNum").html(res.data.warnNum);
    $("#windWarnNum").html(res.data.windWarnNum);

    $("#leanWarnNum").html(res.data.leanWarnNum);
    $("#moveWarnNum").html(res.data.moveWarnNum); //+ " "+res.data.moveWarnNum/res.data.moveTotal*100+"%"
  });

  /*---------------------------------------------top5---------------------------------------------*/

  getData("/biz/dataView/sensorWarnTop", function getCallback(res) {
    echarts_5(res.data);
  });

  /*---------------------------------------------function---------------------------------------------*/
  function echarts_1(monthTime, monthNum) {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById("echarts_1"));
    var monthTime = monthTime;
    var monthNum = monthNum;
    option = {
      tooltip: {
        trigger: "axis",
      },
      legend: {
        orient: "vertical",
        data: ["简易程序案件数"],
      },
      grid: {
        left: "3%",
        right: "3%",
        top: "8%",
        bottom: "5%",
        containLabel: true,
      },
      color: ["#a4d8cc", "#25f3e6"],
      toolbox: {
        show: false,
        feature: {
          mark: { show: true },
          dataView: { show: true, readOnly: false },
          magicType: { show: true, type: ["line", "bar", "stack", "tiled"] },
          restore: { show: true },
          saveAsImage: { show: true },
        },
      },

      calculable: true,
      xAxis: [
        {
          type: "category",

          axisTick: { show: false },

          boundaryGap: false,
          axisLabel: {
            textStyle: {
              color: "#ccc",
              fontSize: "12",
            },
            lineStyle: {
              color: "#2c3459",
            },
            interval: { default: 0 },
            rotate: 50,
            formatter: function (params) {
              var newParamsName = ""; // 最终拼接成的字符串
              var paramsNameNumber = params.length; // 实际标签的个数
              var provideNumber = 4; // 每行能显示的字的个数
              var rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 换行的话，需要显示几行，向上取整
              /**
               * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
               */
              // 条件等同于rowNumber>1
              if (paramsNameNumber > provideNumber) {
                /** 循环每一行,p表示行 */
                var tempStr = "";
                tempStr = params.substring(0, 4);
                newParamsName = tempStr + "..."; // 最终拼成的字符串
              } else {
                // 将旧标签的值赋给新标签
                newParamsName = params;
              }
              //将最终的字符串返回
              return newParamsName;
            },
          },
          data: monthTime,
        },
      ],
      yAxis: {
        type: "value",
        axisLabel: {
          textStyle: {
            color: "#ccc",
            fontSize: "12",
          },
        },
        axisLine: {
          lineStyle: {
            color: "rgba(160,160,160,0.3)",
          },
        },
        splitLine: {
          lineStyle: {
            color: "rgba(160,160,160,0.3)",
          },
        },
      },
      series: [
        {
          // name:'简易程序案件数',
          type: "line",
          areaStyle: {
            normal: {
              type: "default",
              color: new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                0.8,
                [
                  {
                    offset: 0,
                    color: "#25f3e6",
                  },
                  {
                    offset: 1,
                    color: "#0089ff",
                  },
                ],
                false
              ),
            },
          },
          smooth: true,
          itemStyle: {
            normal: { areaStyle: { type: "default" } },
          },
          data: monthNum, //模拟月数据
        },
      ],
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
    window.addEventListener("resize", function () {
      myChart.resize();
    });
  }

  // gaode map
  function gaode_map(Markers) {
    // console.log(Markers, "地图设备");
    mLentght = parseInt(Markers.length / 2);

    // console.log("中心点：", mLentght);
    map = new AMap.Map("map", {
      rotateEnable: false,
      pitchEnable: false,
      viewMode: "3D",
      center: Markers[mLentght].location.split(","),
      // zooms: [2, 17],
      zoom: 14,
      pitch: 65,
      rotation: 10,
      resizeEnable: true,
      mapStyle: "amap://styles/darkblue",
    });
    map.on("complete", function () {
      log.success("数据加载中");
      var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(10, -70) });
      // ----------------------------for----------------------//
      for (let i = 0; i < Markers.length; i++) {
        if (!Markers[i].location) {
          continue;
        } else {
          var iconUrl = "";
          // if (Markers[i].warn == 0) {
          //   iconUrl = "/dataview/img/tticon.png";
          // }
          // if (Markers[i].warn > 2) {
          //   iconUrl = "/dataview/img/tticon.png";
          // }
          let marker = new AMap.Marker({
            map: map,
            icon: Markers[i].icon,
            name: Markers[i].name,
            position: Markers[i].location.split(","),
            offset: new AMap.Pixel(-13, -30),
            data: Markers[i],
          });
          marker.content = "<h1><b>" + Markers[i].name + "</b></h1>";
          marker.content += "<div>最近上报:" + Markers[i].lastUploadTime + "</div>";
          marker.content += "<div>位置:" + Markers[i].address + "</div>";
          marker.content += "<div>负责人:" + Markers[i].dept.leader + "</div>";
          marker.content += "<div>联系电话:" + Markers[i].dept.phone + "</div>";
          marker.content +=
            `&nbsp;<button class="btn btn-warning btn-xs" onclick="javascript:parent.location.href='/biz/sensor?modemId=` +
            Markers[i].modemId +
            `'">查看报警&nbsp;</button>`;
          // marker.content +=
          //   `&nbsp;<button class="btn btn-warning btn-xs video" onclick="getdetil(` +
          //   Markers[i].modemId +
          //   `)" >查看视频&nbsp;</button>`;
         
          marker.extData = Markers[i].modemId;
          marker.setLabel({
            //修改label相对于maker的位置
            offset: new AMap.Pixel(3, -25),
            content: Markers[i].name,
          });
          //点标记事件
          // marker.on("mouseover", (e) => {
          //   infoWindow.setContent(e.target.content);
          //   infoWindow.open(map, e.target.getPosition());
          //   if(loading == 0){
          //     loading = 1;
          //     getData(
          //       "/biz/sensor/list?pageNum=1&pageSize=10&orderByColumn=sensorId&isAsc=desc&enable=1&modemId="+e.target.extData,
          //       function getCallback(res) {
          //         console.log("res", res);
          //         let htm = "";
          //         res.rows.forEach((r) => {
          //           // htm += `<div>` + r.name + `</div>`;
          //           htm += `<tr>
          //                   <td>` + r.name + `</td>
          //                   <td>` + r.msg + `</td>
          //                   <td>` + r.pre + `</td>
          //                   <td>` + r.warn + `</td>
          //                 </tr>`;
          //         });
          //         $("#tbody-left2").html('');
          //         $("#tbody-left2").html(htm);
  
          //         console.log("res2");
          //         loading = 0
          //       }
          //     );
          //   }
          // });

          // marker.on("mouseout", (e) => {
          //   console.log("out");
          //   infoWindow.close(map, e.target.getPosition());
          // });
          marker.on("click", newMAp);
          // newMAp();
          function newMAp(e) {
            console.log(e);
            console.log(e.target._amap_id, "_amap_id");
            map.setCenter(e.target.getPosition());
            map.setZoomAndCenter(15, e.target.getPosition());

            var infoWindow = new AMap.InfoWindow({
              offset: new AMap.Pixel(25, -30),
            });
            infoWindow.setContent(e.target.content);
            infoWindow.open(map, e.target.getPosition());
            if(loading == 0){
              loading = 1;
              getData(
                "/biz/sensor/list?pageNum=1&pageSize=10&orderByColumn=sensorId&isAsc=desc&enable=1&modemId="+e.target.extData,
                function getCallback(res) {
                  console.log("res", res);
                  let htm = "";
                  res.rows.forEach((r) => {
                    // htm += `<div>` + r.name + `</div>`;
                    htm += `<tr>
                            <td>` + r.name + `</td>
                            <td>` + r.msg + `</td>
                            <td>` + r.pre + `</td>
                            <td>` + r.warn + `</td>
                          </tr>`;
                  });
                  $("#tbody-left2").html('');
                  $("#tbody-left2").html(htm);
                  $("#modem_name").html('（'+e.target._originOpts.data.name+' '+e.target._originOpts.data.lastUploadTime+'）');
                  
                  loading = 0
                }
              );
            }
          }
        }
      }
      //------------------------------------------------------//
    });
    map.setFitView();
  }
  //
  function echarts_5(res) {
    // console.log(res, "top5");
    var myChart = echarts.init(document.getElementById("echarts_5"));

    var data = [];
    var xData = [];
    var sensorId = [];
    for (let index = 0; index < res.length; index++) {
      data.push(res[index].warnNum);
      xData.push(res[index].sensorName);
      sensorId.push(res[index].sensorId);
    }

    // var xData = (function (res) {
    //   let d = [];

    //   for (let index = 0; index < res.length; index++) {
    //     d.push(res[index].sensorName);

    //   }

    //   return d;
    // })();
    // var data = [28, 22, 20, 16, 12];
    option = {
      backgroundColor: "#141f56",
      tooltip: {
        show: "true",
        trigger: "item",
        backgroundColor: "rgba(0,0,0,0.4)", // 背景
        padding: [8, 10], //内边距
        extraCssText: "box-shadow: 0 0 3px rgba(255, 255, 255, 0.4);", //添加阴影
        formatter: function (params) {
          if (params.seriesName != "") {
            return params.name + ":" + params.value + "<br>点击查看详情";
          }
        },
      },
      grid: {
        borderWidth: 0,
        top: 20,
        bottom: 35,
        left: 55,
        right: 30,
        textStyle: {
          color: "#fff",
        },
      },
      xAxis: [
        {
          type: "category",

          axisTick: {
            show: false,
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "#363e83",
            },
          },
          axisLabel: {
            inside: false,
            textStyle: {
              color: "#bac0c0",
              fontWeight: "normal",
              fontSize: "12",
            },
            formatter: function (val) {
              return val.split("").join("\n");
            },
          },
          data: xData,
        },
        {
          type: "category",
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: false,
          },
          splitArea: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          data: xData,
        },
      ],
      yAxis: {
        type: "value",
        axisTick: {
          show: false,
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: "#32346c",
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: "#32346c ",
          },
        },
        axisLabel: {
          textStyle: {
            color: "#bac0c0",
            fontWeight: "normal",
            fontSize: "12",
          },
          formatter: "{value}",
        },
      },
      series: [
        {
          // name: '生师比(%)',
          type: "bar",
          itemStyle: {
            normal: {
              show: true,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "#00c0e9",
                },
                {
                  offset: 1,
                  color: "#3b73cf",
                },
              ]),
              barBorderRadius: 50,
              borderWidth: 0,
            },
            emphasis: {
              shadowBlur: 15,
              shadowColor: "rgba(105,123, 214, 0.7)",
            },
          },
          zlevel: 2,
          barWidth: "20%",
          data: data,
        },
        {
          name: "",
          type: "bar",
          xAxisIndex: 1,
          zlevel: 1,
          itemStyle: {
            normal: {
              color: "#121847",
              borderWidth: 0,
              shadowBlur: {
                shadowColor: "rgba(255,255,255,0.31)",
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 2,
              },
            },
          },
          barWidth: "20%",
          data: [30, 30, 30, 30, 30],
        },
      ],
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
    // console.log(window.location.host);
    var url = "http://" + window.location.host;
    myChart.on("click", function (params) {
      console.log(params);
      let index = params.dataIndex;
      console.log(sensorId[index]);

      window.open(url + "/biz/msgSensor?sensorId=" + sensorId[index]);
    });
    window.addEventListener("resize", function () {
      myChart.resize();
    });
  }
});
